package com.als.healthymananger.interceptor;

import com.als.healthymananger.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class GlobalInterceptor implements HandlerInterceptor {
    @Value("${jwt.token-header}")
    private String tokenHeader;
    @Value("${jwt.token-head}")
    private String tokenHead;

    @Autowired
    private JWTUtil jwtUtil;


    // 在目标方法执行之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取jwt头
        String header = request.getHeader(tokenHeader);
        // 获取jwt
        String jwt = header.substring(tokenHead.length()+1);
        // 获取userType
        String username = jwtUtil.getClaim(jwt, "sub");
        request.setAttribute("username", username);
        log.info("username: {}", username);
        return true;
    }
}
